# -*-coding: utf-8 -*-
# by zw on 2017/12/20
import logging
from utils.util import myyaml as yaml
from utils.util import get_valid_yaml, merge_dicts, get_comment_yaml
from sanic import response
from utils.mongo import get_app_config_collection, get_global_template_collection
from utils.util import merge_conf_loose, _render_template

_logger = logging.getLogger(__name__)


# async def get_app_config(request):
#     app_name, env, _json, setting_key = "", "", {}, ""
#     try:
#         app_name = request.raw_args['app_name']
#         setting_key = request.raw_args['setting_key']
#         env = request.raw_args['env']
#         _logger.info("app_name %s env %s host %s", app_name, env, request.host)
#         setting_yaml_str = ""
#         try:
#             doc = get_app_config_collection().find_one({"app_name": app_name}, {"_id": 0})
#             _conf = await merge_conf_loose(doc, env)
#             render_str = _conf[env]
#         except Exception as e:
#             _logger.exception(e)
#         else:
#             _json = get_comment_yaml(render_str)
#             setting_yaml_str = yaml.dump(_json[app_name][setting_key])
#         if not setting_yaml_str:
#             raise ValueError()
#         if setting_yaml_str.find("|-") == 0:
#             setting_yaml_str = setting_yaml_str[2:]

#     except Exception as e:
#         _logger.exception("url %s exception %s app_name %s env %s  _json %s setting_key %s  invalid" % (
#             request.url, e, app_name, env, _json, setting_key))
#         return response.HTTPResponse(body_bytes=b"", status=502)
#     else:
#         return response.HTTPResponse(body_bytes=setting_yaml_str.encode('utf-8'))


async def get_app_global_template(request):
    app_name, env, _json, template_name = "", "", {}, ""
    try:
        app_name = request.raw_args['app_name']
        template_name = request.raw_args['template_name']
        env = request.raw_args['env']
        _logger.info("app_name %s env %s host %s", app_name, env, request.host)
        doc = get_global_template_collection().find_one({"template_name": template_name})
        _yml_str = doc['template']
        render_str = await _render_template(_yml_str, env, app_name)
    except Exception as e:
        _logger.exception("url %s exception %s app_name %s env %s  _json %s template_name %s  invalid" % (
            request.url, e, app_name, env, _json, template_name))
        return response.HTTPResponse(body_bytes=b"", status=502)
    else:
        return response.HTTPResponse(body_bytes=render_str.encode('utf-8'))



async def get_app_config(request):
    app_name, env, _json, setting_key = "", "", {}, ""
    try:
        app_name = request.raw_args['app_name']
        env = request.raw_args['env']
        _logger.info("app_name %s env %s host %s", app_name, env, request.host)
        setting_yaml_str = ""
        try:
            doc = get_app_config_collection().find_one({"app_name": app_name}, {"_id": 0})
            setting_yaml_str = doc['env_config_%s' % (env)]            
        except Exception as e:
            _logger.exception(e)
        
        if not setting_yaml_str:
            raise ValueError()
    except Exception as e:
        _logger.exception("url %s exception %s app_name %s env %s  _json %s setting_key %s  invalid" % (
            request.url, e, app_name, env, _json, setting_key))
        return response.HTTPResponse(body_bytes=b"", status=502)
    else:
        return response.HTTPResponse(body_bytes=setting_yaml_str.encode('utf-8'))
